<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use DateTimeInterface;

class Crm_Gift_Record extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasFactory;

    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'crm_gift_record';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'agencyid',
        'giftid',
        'mid',
        'otherid',
        'fee',
        'nums',
        'total_fee',
        'is_del'
    ];

    protected $appends = ['giftName','giftUrl'];

    public function getGiftNameAttribute()
    {
        if ($this->giftid){
            return $this->hasOneGift->giftname;
        }else{
            return '';
        }
    }

    public function getGiftUrlAttribute()
    {
        if ($this->giftid){
            return $this->hasOneGift->url;
        }else{
            return '';
        }
    }

    protected $hidden = [
        'is_del',
    ];

    public function scopeNodel($query)
    {
        return $query->where('is_del', 'N');
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function hasOneMember()
    {
        return $this->hasOne('App\Models\Crm_Member', 'id', 'mid');
    }

    public function hasOneOtherMember()
    {
        return $this->hasOne('App\Models\Crm_Member', 'id', 'otherid');
    }

    public function hasOneGift()
    {
        return $this->hasOne('App\Models\Crm_Gift', 'id', 'giftid');
    }

    public static function getFilter($filter)
    {
        return self::whereHas('hasOneGift',function ($q) use ($filter){
            if (isset($filter['giftname']) && !empty($filter['giftname'])) {
                $q->where('giftname', 'LIKE', '%'.$filter['giftname'].'%');
            }

        })->whereHas('hasOneMember',function ($q) use ($filter){
            if (isset($filter['username']) && !empty($filter['username'])) {
                $q->where('username', 'LIKE', '%'.$filter['username'].'%');
            }

        })->where(function ($query) use ($filter){
            if (isset($filter['mid']) && !empty($filter['mid'])) {
                $query->where('mid', $filter['mid']);
            }
            if (isset($filter['otherid']) && !empty($filter['otherid'])) {
                $query->where('otherid', $filter['otherid']);
            }
            $query->where('agencyid', $filter['aid']);
        })->orderBy('id', 'desc');
    }

}
